package com.hui.forecastapp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.hui.forecastapp.city_manager.CityManagerActivity;
import com.hui.forecastapp.db.DBManager;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    ImageView addCityIv, moreIv;
    LinearLayout pointLayout;
    ViewPager mainVp;
    // ViewPage的数据源
    List<Fragment> fragmentList;
    // 表示选中的城市的集合
    List<String> provinceList;
    List<String> cityList;
    // 表示ViewPage的页数指数器显示集合
    List<ImageView> imgList;

    private CityFragmentPagerAdapter adapter;

    RelativeLayout outLayout;
    private SharedPreferences pref;
    private int bgNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        addCityIv = findViewById(R.id.main_iv_add);
        moreIv = findViewById(R.id.main_iv_more);
        pointLayout = findViewById(R.id.main_layout_point);
        mainVp = findViewById(R.id.main_vp);
        outLayout = findViewById(R.id.main_out_layout);

        addCityIv.setOnClickListener(this);
        moreIv.setOnClickListener(this);

        fragmentList = new ArrayList<>();
        provinceList = DBManager.queryAllProvinceName();
        cityList = DBManager.queryAllCityName();
        imgList = new ArrayList<>();

        exchangeBg();

        // 如果数据库中没有数据则添加为北京
        if(cityList.size() == 0) {
            provinceList.add("北京");
            cityList.add("北京");
        }

        // 因为可能搜索界面点击跳转到此界面，且会传值，所以在此处尝试获取信息
        try {
            Intent intent = getIntent();
            String province = intent.getStringExtra("province");
            String city = intent.getStringExtra("city");
            //        Log.d(province + " ???  " + city, "MainActivity");
            if (!TextUtils.isEmpty(city) && !TextUtils.isEmpty(province)) {
                if (!cityList.contains(city)) {
                    provinceList.add(province);
                    cityList.add(city);
                }
            }
        } catch (Exception e){
            Log.i("animee","程序出现问题了！！");
        }

        // 初始化ViewPage页面的方法
        initPager();
        adapter = new CityFragmentPagerAdapter(getSupportFragmentManager(), fragmentList);
        mainVp.setAdapter(adapter);

        // 创建小圆点指示器
        initPoint();
        // 设置显示最后一个城市信息
        mainVp.setCurrentItem(fragmentList.size() - 1);
        // 设置ViewPager页面监听
        setPagerListener();
    }

    // 换壁纸的函数
    public void exchangeBg() {
        pref = getSharedPreferences("bg_pref", MODE_PRIVATE);
        bgNum = pref.getInt("bg", 2);
        switch (bgNum) {
            case 0:
                outLayout.setBackgroundResource(R.mipmap.bg);
                break;
            case 1:
                outLayout.setBackgroundResource(R.mipmap.bg2);
                break;
            case 2:
                outLayout.setBackgroundResource(R.mipmap.bg3);
                break;
        }
    }

    private void setPagerListener() {
        // 设置监听事件
        mainVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                // 改变下方圆点
                for (int i = 0; i < imgList.size(); i++) {
                    imgList.get(i).setImageResource(R.mipmap.a1);
                }
                imgList.get(position).setImageResource(R.mipmap.a2);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initPoint() {
        // 创建小圆点
        for (int i = 0; i < fragmentList.size(); i++) {
            ImageView pIv = new ImageView(this);
            pIv.setImageResource(R.mipmap.a1);
            pIv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) pIv.getLayoutParams();
            lp.setMargins(0, 0, 20, 0);
            imgList.add(pIv);
            pointLayout.addView(pIv);
        }
        // 默认最后一个被选中
        imgList.get(imgList.size() - 1).setImageResource(R.mipmap.a2);
    }

    private void initPager() {
        // 创建Fragment对象，添加到ViewPager数据源当中
        for (int i = 0; i < cityList.size(); i++) {
            CityWeatherFragment cityWeatherFragment = new CityWeatherFragment();
            Bundle bundle = new Bundle();
            bundle.putString("province", provinceList.get(i));
            bundle.putString("city", cityList.get(i));
            cityWeatherFragment.setArguments(bundle);
            fragmentList.add(cityWeatherFragment);
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.main_iv_add:
                intent.setClass(this, CityManagerActivity.class);
                break;
            case R.id.main_iv_more:
                intent.setClass(this, MoreActivity.class);
                break;
        }
        startActivity(intent);
    }

    // 当页面重新加载时调用的函数，在获取焦点之前调用，此处完成ViewPager页数的更新
    @Override
    protected void onRestart() {
        super.onRestart();
        // 获取数据库当中剩下的城市列表
        List<String> listProvince = DBManager.queryAllProvinceName();
        List<String> listCity = DBManager.queryAllCityName();
        if (listCity.size() == 0) {
            listProvince.add("北京");
            listCity.add("北京");
        }
        // 重新加载之前清空之前的数据源
        provinceList.clear();
        cityList.clear();

        provinceList.addAll(listProvince);
        cityList.addAll(listCity);

        // 剩余城市也要创建对应的Fragment页面
        fragmentList.clear();
        initPager();
        adapter.notifyDataSetChanged();

        // 页面数量发生改变，指示器的数量也要改变(小圆点)
        imgList.clear();
        // 将布局当中所有元素全部移除
        pointLayout.removeAllViews();
        initPoint();
        mainVp.setCurrentItem(fragmentList.size() - 1);
    }
}